package com.hanagent.controller;

import com.alibaba.fastjson.JSONObject;
import com.hanagent.model.Admins;
import com.hanagent.model.Agents;
import com.hanagent.model.Moneyrecords;
import com.hanagent.model.Postals;
import com.hanagent.utils.ConstantUtils;
import com.hanagent.utils.DateUtils;
import com.hanagent.utils.MoneyUtils;
import com.hanagent.utils.ResponseUtils;
import com.hanagent.utils.StrUtils;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class PostalsController extends Controller{

	public void getList() {
		int pageNumber = getParaToInt("pageNumber")<1?1:getParaToInt("pageNumber");
		int pageSize = getParaToInt("pageSize")<1?1:getParaToInt("pageSize");
		String startCreateTime = getPara("startCreateTime");
		if (StrUtils.isEmpty(startCreateTime)) {
			startCreateTime = "1917-12-05T16:00:00.000Z";
		} 
		String endCreateTime = getPara("endCreateTime");
		if (StrUtils.isEmpty(endCreateTime)) {
			endCreateTime = "3017-12-05T16:00:00.000Z";
		}  
		String startUpdateTime = getPara("startUpdateTime");
		if (StrUtils.isEmpty(startUpdateTime)) {
			startUpdateTime = "1917-12-05T16:00:00.000Z";
		} 
		String endUpdateTime = getPara("endUpdateTime");
		if (StrUtils.isEmpty(endUpdateTime)) {
			endUpdateTime = "3017-12-05T16:00:00.000Z";
		} 
		
		String agentId = getPara("agentId");
		Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
		
		double allPostMoney = 0;
		double allPostMoneyWaitReView = 0;
		double allPostMoneyPass = 0;
		double allPostMoneyRefused = 0;
		Page<Postals> list = null;
		if (StrUtils.isEmpty(agentId)) {
			if (loginAgents.getAgentLevel()>ConstantUtils.LevelCompanySource){
				list = Postals.dao.paginate(pageNumber, pageSize, "select Postals.* , Agents.agentMan", "from Postals INNER JOIN Agents ON Postals.userId = "
									+ "Agents.agentId where Postals.createdAt > ? and "
						+ "Postals.createdAt < ? and Postals.updatedAt > ? and Postals.updatedAt < ? and Postals.userId = ? order by Postals.updatedAt desc",
						startCreateTime, endCreateTime, startUpdateTime, endUpdateTime, loginAgents.getAgentId());
				
				allPostMoney = getDatePrice(loginAgents.getAgentId()+"", "", startCreateTime, endCreateTime);
				allPostMoneyWaitReView = getDatePrice(loginAgents.getAgentId()+"", ConstantUtils.StateAgentWaitReView+"", startCreateTime, endCreateTime);
				allPostMoneyPass = getDatePrice(loginAgents.getAgentId()+"", ConstantUtils.StateAgentPass+"", startCreateTime, endCreateTime);
				allPostMoneyRefused = getDatePrice(loginAgents.getAgentId()+"", ConstantUtils.StateAgentRefused+"", startCreateTime, endCreateTime);
				
			}else{
				list = Postals.dao.paginate(pageNumber, pageSize, "select Postals.* , Agents.agentMan ", "from Postals INNER JOIN Agents ON Postals.userId = "
									+ "Agents.agentId where Postals.createdAt > ? and "
						+ "Postals.createdAt < ? and Postals.updatedAt > ? and Postals.updatedAt < ? order by Postals.updatedAt desc",
						startCreateTime, endCreateTime, startUpdateTime, endUpdateTime);
				
				allPostMoney = getDatePrice("", "", startCreateTime, endCreateTime);
				allPostMoneyWaitReView = getDatePrice("", ConstantUtils.StateAgentWaitReView+"", startCreateTime, endCreateTime);
				allPostMoneyPass = getDatePrice("", ConstantUtils.StateAgentPass+"", startCreateTime, endCreateTime);
				allPostMoneyRefused = getDatePrice("", ConstantUtils.StateAgentRefused+"", startCreateTime, endCreateTime);
			}
		}else{
			if (loginAgents.getAgentLevel()>ConstantUtils.LevelCompanySource && !agentId.equals(loginAgents.getAgentId()+"")) {
				renderText(ResponseUtils.sendResult(0, "", "你无权查看其他代理商的提现记录"));
				return;
			}
			
			list = Postals.dao.paginate(pageNumber, pageSize, "select Postals.* , Agents.agentMan ", "from Postals INNER JOIN Agents ON Postals.userId = "
									+ "Agents.agentId  where Postals.createdAt > ? and "
					+ "Postals.createdAt < ? and Postals.updatedAt > ? and Postals.updatedAt < ? and Postals.userId = ? order by Postals.updatedAt desc",
					startCreateTime, endCreateTime, startUpdateTime, endUpdateTime, agentId);
			
			allPostMoney = getDatePrice(agentId+"", "", startCreateTime, endCreateTime);
			allPostMoneyWaitReView = getDatePrice(agentId+"", ConstantUtils.StateAgentWaitReView+"", startCreateTime, endCreateTime);
			allPostMoneyPass = getDatePrice(agentId+"", ConstantUtils.StateAgentPass+"", startCreateTime, endCreateTime);
			allPostMoneyRefused = getDatePrice(agentId+"", ConstantUtils.StateAgentRefused+"", startCreateTime, endCreateTime);
		}
		
		JSONObject object = new JSONObject();
		object.put("allPostMoney", allPostMoney);
		object.put("allPostMoneyWaitReView", allPostMoneyWaitReView);
		object.put("allPostMoneyPass", allPostMoneyPass);
		object.put("allPostMoneyRefused", allPostMoneyRefused);
		object.put("listData", list); 
		
		renderText(ResponseUtils.sendResult(1, object, "获取数据成功"));
	}
	
	private double getDatePrice(String agentId, String state, String startCreateTime, String endCreateTime){
		Record datePriceSum = null;
		if (StrUtils.isEmpty(agentId)) {
			if (StrUtils.isEmpty(state)) {
				datePriceSum = Db.findFirst("select sum(postalMoney) as datePrice from Postals where "
						+"createdAt > '" + startCreateTime + "' and createdAt < '" + endCreateTime +"'");
			}else{
				datePriceSum = Db.findFirst("select sum(postalMoney) as datePrice from Postals where " 
						+"state like "+ state +" and createdAt > '" + startCreateTime + "' and createdAt < '" + endCreateTime +"'");
			}
		}else{
			if (StrUtils.isEmpty(state)) {
				datePriceSum = Db.findFirst("select sum(postalMoney) as datePrice from Postals where userId="+ agentId 
						+" and createdAt > '" + startCreateTime + "' and createdAt < '" + endCreateTime +"'");
			}else{
				datePriceSum = Db.findFirst("select sum(postalMoney) as datePrice from Postals where userId="+ agentId 
						+" and state like "+ state +" and createdAt > '" + startCreateTime + "' and createdAt < '" + endCreateTime +"'");
			}
		}
		double datePrice = 0; 
		if (datePriceSum.get("datePrice")!=null) {
			datePrice =  datePriceSum.getDouble("datePrice");
		}
		return datePrice;
	}
	
	/**
	 * 添加转余额  或者转账到银行卡
     */  
    public void addPostals() {  
    	Postals postals = getModel(Postals.class, "");//别名  Jfinal 必杀技快速开发全靠它  
    	Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
    	
    	postals.setState(ConstantUtils.StateAgentWaitReView);
    	int postalType = postals.getPostalType();
    	if (postalType==ConstantUtils.TypePostalEMoney) {//转出余额
    		if (postals.get("postalMoney") ==null || postals.getPostalMoney()==0) {
	    		renderText(ResponseUtils.sendResult(0, "", "转出失败，请输入转出金额")); 
	    		return;
			}
	    	
	    	if ( postals.get("postalMoney") ==null || postals.getPostalMoney()%100!=0) {
	    		renderText(ResponseUtils.sendResult(0, "", "转出失败，转出金额必须为100的倍数")); 
	    		return;
			}
	    	
	    	if (MoneyUtils.getCanPostal(loginAgents.getAgentId())<postals.getPostalMoney()) {
	    		renderText(ResponseUtils.sendResult(0, "", "转出失败，转出金额不得超过可提现余额")); 
	    		return;
			}
	    	
	    	String eMoneyMan = getPara("eMoneyMan");
	    	String eMoneyPhone = getPara("eMoneyPhone");
	    	if (loginAgents.getAgentPhone().equalsIgnoreCase(eMoneyPhone)  ) {
	    		renderText(ResponseUtils.sendResult(0, "", "转出失败，不可转出给自己")); 
	    		return;
			}
	    	Agents agentsReceive = Agents.dao.findFirst("select * from agents where agentMan='" + eMoneyMan + "' and agentPhone='"+eMoneyPhone+"'");
	    	if (agentsReceive==null) {
	    		renderText(ResponseUtils.sendResult(0, "", "转出失败，查询不到接收代理商，请检查姓名与电话")); 
	    		return;
			}else{
	    		//添加接收代理商的收益
				String desc2 = loginAgents.getAgentMan()+"转出"+postals.getPostalMoney()+"元余额";
				new Moneyrecords().set("type", ConstantUtils.MonneyTypeBalanceExChange).set("moneyCount", postals.getPostalMoney())
				.set("fromId", postals.getPostalId()).set("desc", desc2).set("userOrAgentId", agentsReceive.getAgentId()).set("userType", "2").save();
			}
	    	
	    	postals.setState(ConstantUtils.StateAgentPass);
	    	
		}else{ //提现到银行卡
			if (postals.get("postalMoney") ==null || postals.getPostalMoney()==0) {
	    		renderText(ResponseUtils.sendResult(0, "", "添加提现失败，请输入提现金额")); 
	    		return;
			}
	    	
	    	if ( postals.get("postalMoney") ==null || postals.getPostalMoney()%100!=0) {
	    		renderText(ResponseUtils.sendResult(0, "", "添加提现失败，提现金额必须为100的倍数")); 
	    		return;
			}
	    	
	    	if (MoneyUtils.getCanPostal(loginAgents.getAgentId())<postals.getPostalMoney()) {
	    		renderText(ResponseUtils.sendResult(0, "", "提现失败，提现金额不得超过可提现余额")); 
	    		return;
			}
		}
    	
    	postals.setUserId(loginAgents.getAgentId());
    	postals.setReviewReason(getPara("reviewReason"));
    	postals.setUserType(2);
        boolean flag = postals.save();  
        if (flag) {  
        	renderText(ResponseUtils.sendResult(1, "", "添加成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "添加失败"));  
        }  
    }

    /** 
     * 审核
     */   
    public void reviewPostals() {  
    	int postalId = getParaToInt("postalId");
    	int state = getParaToInt("state");
    	Agents loginAgents = getAttr("loginAgents"); //登陆的代理商
    	if (loginAgents.getAgentLevel()!=ConstantUtils.LevelSuper) {
			renderText(ResponseUtils.sendResult(0, "", "只有公司管理员才可以审核其他代理商的提现"));
			return;
		}
    	Postals postals = Postals.dao.findById(postalId);
    	if (postals.getState()!=ConstantUtils.StateAgentWaitReView) {
    		renderText(ResponseUtils.sendResult(0, "", "只可审核未审核的提现"));
			return;
		}
    	if (postals.getState()==ConstantUtils.StateAgentRefused) {
    		String reviewReason = getPara("reviewReason");
    		if (StrUtils.isEmpty(reviewReason)) {
    			renderText(ResponseUtils.sendResult(0, "", "驳回请输入驳回原因")); 
    			return;
			}
		}
    	Admins admins = getAttr("loginAdmins");
    	postals.setReviewedUserId(admins.getAdminId());
    	postals.setReviewedUserName(admins.getAdminName());
    	postals.setReviewReason(getPara("reviewReason"));
    	boolean flag = postals.set("state", state).update(); 
        if (flag) {  
        	if (postals.getState()==ConstantUtils.StateAgentPass) { //审核通过3%为手续费
        		Agents postalAgents = Agents.dao.findById(postals.getUserId());
        		int moneyCount2 = (int) (postals.getPostalMoney()*0.03);
				String desc2 = ""; 
				desc2 = "("+postalAgents.getAgentMan()+")"+postals.getPostalMoney()+"元提现的3%提现手续费";
				new Moneyrecords().set("type", ConstantUtils.MonneyTypePostalLevel).set("moneyCount", moneyCount2).set("fromId", postals.getPostalId()).set("desc", desc2)
            	.set("userOrAgentId", postals.getUserId()).set("userType", "2").save();
			}
        	renderText(ResponseUtils.sendResult(1, "", "操作成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "操作失败"));  
        }   
    }
    
    /** 
     * 修改 
     */   
    public void updatePostals() {  
    	Postals postals = getModel(Postals.class, "");//别名  Jfinal 必杀技快速开发全靠它  
    	postals.setUpdatedAt(DateUtils.getNowDateWith8());
        boolean flag = postals.update();
        if (flag) {  
        	renderText(ResponseUtils.sendResult(1, "", "添加成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "添加失败"));  
        }   
    }  
      
    /** 
     * 删除单个 
     */  
    public void delPostalsById() {  
        Integer id = getParaToInt("postalId");  
        boolean flag = Postals.dao.deleteById(id);  
        if (flag) {  
        	renderText(ResponseUtils.sendResult(1, "", "删除成功"));  
        }else {  
        	renderText(ResponseUtils.sendResult(0, "", "删除失败"));  
        }    
    }
	
}
